package nxu.it.movieapi.service.pg;

import nxu.it.api.common.result.BasePage;
import nxu.it.api.common.result.Pageable;
import nxu.it.api.model.CastRole;
import nxu.it.api.model.Filmography;
import nxu.it.api.model.SimpleStaff;
import nxu.it.api.model.Staff;
import nxu.it.api.service.MovieCastService;
import nxu.it.api.service.StaffService;
import nxu.it.api.service.param.StaffPageQueryParam;
import nxu.it.movieapi.service.pg.dao.StaffDao;
import nxu.it.movieapi.service.pg.entity.StaffEntity;
import nxu.it.movieapi.service.pg.mapper.StaffMapper;
import org.seasar.doma.jdbc.SelectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Optional;

@Component
public class StaffServicePgImpl implements StaffService {
    @Autowired
    StaffDao staffDao;
    @Autowired
    StaffMapper staffMapper;
    @Autowired
    MovieCastService movieCastService;

    @Override
    public Optional<Staff> findById(@NotNull Integer staffId) {
        return staffDao.findById(staffId)
                .map(staffEntity ->{
                    Staff staff = staffMapper.fromEntity(staffEntity);
                    List<Filmography> acted = movieCastService
                            .findMoviesByStaffIdAndRole(staffId, CastRole.ACTOR);
                    List<Filmography> directed=movieCastService
                            .findMoviesByStaffIdAndRole(staffId, CastRole.DIRECTOR);
                    staff.setActed(acted);
                    staff.setDirected(directed);
                    return staff;
                } );
    }

    @Override
    public Pageable<SimpleStaff> page(@NotNull StaffPageQueryParam staffPageQueryParam) {
        int totalRow = staffDao.getTotalRow(staffPageQueryParam);
        int pagesize =staffPageQueryParam.getPageSize();
        int pageNumber = staffPageQueryParam.getPageNumber();
        PageUtil.setOneAsFirstPageNo();
        int totalPage = PageUtil.getTotalPage(totalRow, pagesize);
        int start = PageUtil.getOffset(pageNumber, pagesize);
        SelectOptions options=SelectOptions.get();
        options.limit(pagesize).offset(start);
        List<StaffEntity> staffEntityList = staffDao.page(staffPageQueryParam, options);
        List<Staff> stafflist =staffMapper.fromEntitylist(staffEntityList);
        List<SimpleStaff> simpleStaffList = staffMapper.tosimplestafflist(stafflist);
        Pageable<SimpleStaff> simpleStaffPage = new BasePage<>(simpleStaffList, pageNumber, pagesize, totalPage, totalRow);

        return simpleStaffPage;

    }


}
